import React, { useState } from 'react';
import {
    TextField,
    InputAdornment,
    IconButton,
    FormHelperText,
    FormControl
} from '@mui/material';
import { styled } from '@mui/material/styles';
import { Visibility, VisibilityOff } from '@mui/icons-material';
import { motion } from 'framer-motion';

const StyledFormControl = styled(FormControl)(({ theme }) => ({
    width: '100%',
    marginBottom: theme.spacing(2),
}));

// 使用Framer Motion增强的TextField
const MotionTextField = motion(TextField);

const FormInput = ({
    label,
    name,
    value,
    onChange,
    type = 'text',
    error = null,
    icon = null,
    ...props
}) => {
    const [showPassword, setShowPassword] = useState(false);
    const isPassword = type === 'password';

    // 切换密码可见性
    const handleTogglePassword = () => {
        setShowPassword((prevState) => !prevState);
    };

    return (
        <StyledFormControl error={!!error}>
            <MotionTextField
                fullWidth
                label={label}
                name={name}
                type={isPassword && showPassword ? 'text' : type}
                value={value}
                onChange={onChange}
                error={!!error}
                variant="outlined"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{
                    duration: 0.3,
                    delay: 0.1
                }}
                InputProps={{
                    startAdornment: icon && (
                        <InputAdornment position="start">
                            {icon}
                        </InputAdornment>
                    ),
                    endAdornment: isPassword && (
                        <InputAdornment position="end">
                            <IconButton
                                aria-label="toggle password visibility"
                                onClick={handleTogglePassword}
                                edge="end"
                            >
                                {showPassword ? <VisibilityOff /> : <Visibility />}
                            </IconButton>
                        </InputAdornment>
                    )
                }}
                {...props}
            />
            {error && (
                <FormHelperText error>
                    {error}
                </FormHelperText>
            )}
        </StyledFormControl>
    );
};

export default FormInput; 